package com.hank.activemq.plugins;

import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerFilter;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.command.ConnectionInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ClientConnAcl extends BrokerFilter {

    private static final Logger log = LoggerFactory.getLogger(ClientConnAcl.class);


    Pattern pattern = Pattern.compile("^([0-9\\.]*):(.*)");

    public ClientConnAcl(Broker broker) {
        super(broker);
    }

    @Override
    public void addConnection(ConnectionContext context,
                              ConnectionInfo info) throws Exception {
        String remoteAddress = context.getConnection().getRemoteAddress();
        System.out.println("连接客户端:" + remoteAddress + ">" + info);
        log.info("连接客户端:" + remoteAddress);
        //remoteAddress的形式如：tcp://127.0.0.1: 6572，由于正则表达式用得不好，在此截取127.0.0.1: 6572来判断
        //这个正则表达式怎么用，欢迎赐教
        Matcher matcher = pattern.matcher("");

        // 拒绝连接
        if(auth(info.getUserName(), info.getPassword())) {
            log.info("验证通过,允许连接:>>ClientID=" + info.getClientId() + " ip:" + info.getClientIp());
        }
        super.addConnection(context, info);
    }

    private boolean auth(String userName, String password) {
        if ("abc".equals(userName) || "abc".equals(password)) {
            return true;
        }else{
            log.error("验证失败!");
            throw new SecurityException("Invalid  userName or password!");
        }
    }
}
